package com.dfec.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.dfec.model.Msg;
import com.dfec.model.User;
import com.dfec.service.IUserService;
import com.dfec.service.imp.UserServiceImp;
import com.dfec.utils.Consists;
import com.dfec.utils.ResponseUtil;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(name = "login", description = "用户登录", urlPatterns = { "/login" })
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private IUserService ius=new UserServiceImp();
	 Msg msg=null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  String user_phone= request.getParameter("user_phone");
	  String user_pass=  request.getParameter("user_pass");
	  String action=  request.getParameter("action");
	  List<Object> list =new ArrayList<>();
	  User  user = null;
	  msg=new Msg();
	  if(action.equals("cheackUser")) {
		  user=ius.getUserByPhone(new User(user_phone,user_pass));
	  }else if(action.equals("login")) {
		  user=ius.login(new User(user_phone,user_pass));
	  }
	   
	
	  
	  if(user!=null) {
		  msg.setCode(Consists.Error_Code_OK);
		  msg.setMsg(Consists.Error_Msg__LOGIN_OK);
	  }else {
		  msg.setCode(Consists.Error_Code_FAIL);
		  msg.setMsg(Consists.Error_Msg__LOGIN_FAIL);
	  }
	  list.add(msg);
	  list.add(user);
	  ResponseUtil.sendScript(response, JSON.toJSONString(list));
	}

}
